import xbmc, xbmcgui, xbmcplugin, urllib2, urllib, re, sys, os, time

baseurl = 'http://svtplay.se'

def getData(url):
	request = urllib2.Request(url)
	request.add_header = [('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')]
	response = urllib2.urlopen(request)
	data = response.read()
	response.close();

	return data

def getParams():
	param=[]
	params=sys.argv[2]
	if len(params)>=2:
		params=params[0:len(params)-2]
		pairs=params.replace('?','').split('&')
		param = {}
		for i in range(len(pairs)):
			split=pairs[i].split('=')
			if (len(split))==2:
				param[split[0]]=split[1]

	return param

def getStartItems():
	addListItem('Program A-Ö', baseurl + '/alfabetisk', "list-ao")
	addListItem('Kategorier', baseurl + "/kategorier", "categories")
	return

def getProgramsAO(url):
	data = getData(url)
	programs = re.compile('<li>\W+<a href="([^"]+)">([^<]+)</a>\W+</li>').findall(data, re.DOTALL)
	
	for purl, title in programs:
		addListItem(decodeHtmlEntities(title), baseurl+purl, "parts")

	return
	
def getCategories(url):
	data = getData(url)
	ul = re.compile('<ul class="list category-list[^"]*">[\W\w]+?</ul>').findall(data, re.DOTALL)[0]
	categories = re.compile('<li class="[^"]*">\W+<div class="container">\W*<a href="([^"]+)"[^>]*>\W*<img[^>]+src="([^"]+)[^>]+>\W*<span class="bottom"></span>\W*<span class="[^"]*">([^>]+)</span>').findall(ul, re.DOTALL)

	for curl, image, title in categories:
		if (curl[0] != "/"):
			curl = "/"+curl

		addListItem(decodeHtmlEntities(title), baseurl + curl, "categoryprograms", image)

def getCategoryPrograms(url):
	data = getData(url)
	uls = re.compile('<ul class="list[^"]*">[\W\w]+?</ul>').findall(data, re.DOTALL)
	pagecount = int(re.compile('<ul class="list {pagenum:(\d+)[^"]*">[\W\w]+?</ul>').findall(data, re.DOTALL)[0])

	for ul in uls:
		programs = re.compile('<li class="[^"]*">\W*<a href="([^"]+)"[^>]*>\W*<img[^>]+src="([^"]+)[^>]+>\W*(<!--[^/]+/span -->\W+){0,1}<span>([^>]+)</span>').findall(ul, re.DOTALL)

		for purl, image, co, title in programs:
			if (purl[0] != "/"):
				purl = "/"+purl
		
			addListItem(decodeHtmlEntities(title.strip()), baseurl + purl, "parts", image)
		
	it = url[url.rindex('/') + 1:len(url)].split(',')
	
	
	if len(it) == 1:
		it = ["pb", "a1364150", "1", "f", "-1"]

	current = int(it[2])
	if (current < pagecount):
		it[2] = str(current + 1)
		addListItem("Nästa sida...", "http://svtplay.se/c/96251/barn?ajax,pb/" + ','.join(it), "categoryprograms")

def getProgramParts(url):
	data = getData(url)
	ul = re.compile('<ul class="navigation playerbrowser">[\W\w]+?</ul>').findall(data, re.DOTALL)[0]
	parts = re.compile('<li class="[^"]*">\W+(<h2>)*\W*<a href="([^"]+)"[^>]+>([^<]+)</a>').findall(ul, re.DOTALL)
	if len(parts) == 1:
		getEpisodes(url+urllib.unquote_plus(parts[0][1]))
	else:
		for h2, purl, title in parts:
			if (purl[0] != "/"):
				purl = "/" + purl

			addListItem(decodeHtmlEntities(title), url + purl, "episodes")
	return

def getEpisodes(url):
	data = getData(url)
	pagecount = int(re.compile('<ul class="list small[^"]*pagenum:(\d+)[^"]*">[\W\w]+?</ul>').findall(data, re.DOTALL)[0])
	ul = re.compile('<ul class="list small[^"]*">[\W\w]+?</ul>').findall(data, re.DOTALL)[0]
	
	episodes = re.compile('<li class="[^"]*"\W*>\W+<a href="([^"]+)"[^>]+title="([^"]*)"[^>]+>\W+<img[^>]+src="([^"]+)[^>]+>\W+(<!--[^/]+/span -->\W+){0,1}<span[^>]*>([^<]+)</span>').findall(ul, re.DOTALL)
	for purl, info, image, comment, title in episodes:
		if purl[0:7] != "http://":
			addListItem(title.strip(), baseurl + purl, "play", image, False)

	it = url[url.rindex('/') + 1:len(url)].split(',')
	current = int(it[2])
	
	if (current < pagecount):
		it[2] = str(current + 1)
		addListItem("Nästa sida...", url[0:url.rindex('/') + 1] + ','.join(it), "episodes")

	return

def play(url,name):
	data = getData(url)
	videolink = re.compile('pathflv=([^&]+)').findall(data, re.DOTALL)[0]
	
	item=xbmcgui.ListItem(name, iconImage='', thumbnailImage='')
	item.setInfo(type="Video", infoLabels={ "Title": name})
	xbmc.Player(xbmc.PLAYER_CORE_DVDPLAYER).play(videolink, item)


def addListItem(name,url,mode,iconimage='',folder=True):
	u = sys.argv[0] + "?url=" + urllib.quote_plus(url) + "&mode=" + urllib.quote_plus(mode) + "&name=" + urllib.quote_plus(name)
	li=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
	li.setInfo(type="Video", infoLabels={ "Title": name })
	return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=li, isFolder=folder)


def decodeHtmlEntities(string):
	return string.replace("&amp;", "&")

params=getParams()
url=None
name=None
mode=None

try:
	url=urllib.unquote_plus(params["url"])
except:
	pass

try:
        name=urllib.unquote_plus(params["name"])
except:
	pass

try:
        mode=urllib.unquote_plus(params["mode"])
except:
	pass

if mode==None or url==None or len(url)<1:
        getStartItems()
        xbmcplugin.endOfDirectory(int(sys.argv[1]))
if mode=="list-ao":
        getProgramsAO(url)
        xbmcplugin.endOfDirectory(int(sys.argv[1]))
if mode=="categories":
        getCategories(url)
        xbmcplugin.endOfDirectory(int(sys.argv[1]))
if mode=="categoryprograms":
        getCategoryPrograms(url)
        xbmcplugin.endOfDirectory(int(sys.argv[1]))
elif mode=="parts":
        getProgramParts(url)
        xbmcplugin.endOfDirectory(int(sys.argv[1]))
elif mode=="episodes":
        getEpisodes(url)
        xbmcplugin.endOfDirectory(int(sys.argv[1]))
elif mode=="play":
        play(url,name)




